package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.GroupService;
import com.fz.us.admin.company.service.PowerService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 岗位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/group")
public class GroupController extends BaseController {


    private static final long serialVersionUID = 7986955188625840236L;
    @Autowired
    private GroupService groupService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private UserService userService;
    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user) {

        return "/main/company/group_input";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {
        if(StringUtils.isNotEmpty(keyId)){
            Group group =groupService.get(keyId);
            model.addAttribute("group", group);
        }
        model.addAttribute("keyId", keyId);
        return "/main/company/group_input";
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,  String usersId, String departId, String powerId,
                       Group group) {
        // 必填校验
        if (StringUtils.isBlank(group.getName())) {
            return resultService.fail("名称不能为空");
        }
        // 必填校验
        if (StringUtils.isBlank(group.getName())) {
            return resultService.fail("别名不能为空");
        }
        //用户
        Set<User> usersSet = null;
        if (StringUtils.isNotEmpty(usersId)){
            String arr[] = usersId.split(",");
            usersSet = new HashSet<User>();
            for (int i=0; i<arr.length;i++){
                User users = userService.get(arr[i]);
                if (users != null){
                    usersSet.add(users);
                }
            }
        }
        group.setUsersSet(usersSet);
        //部门
        Set<Department> departmentsSet = null;
        if (StringUtils.isNotEmpty(departId)){
            String arr[] = departId.split(",");
            departmentsSet = new HashSet<Department>();
            for (int i=0; i<arr.length;i++){
                Department department = departmentService.get(arr[i]);
                if (department != null){
                    departmentsSet.add(department);
                }
            }
        }
        group.setDepartSet(departmentsSet);
        //职权
        Set<Power> powersSet = null;
        if (StringUtils.isNotEmpty(powerId)){
            String arr[] = powerId.split(",");
            powersSet = new HashSet<Power>();
            for (int i=0; i<arr.length;i++){
                Power power = powerService.get(arr[i]);
                if (power != null){
                    powersSet.add(power);
                }
            }
        }
        group.setPowerSet(powersSet);
        if (StringUtils.isBlank(keyId)) {// 保存
            Company company = user.getCompany();
            group.setCompany(company);
            return ajaxJson(groupService.saveEntity(group));
        } else {// 修改
            Group groupTmp = groupService.get(keyId);
            groupTmp.setName(group.getName());
            groupTmp.setpName(group.getpName());
            groupTmp.setDescription(group.getDescription());
            groupTmp.setUsersSet(group.getUsersSet());
            groupTmp.setDepartSet(group.getDepartSet());
            groupTmp.setPowerSet(group.getPowerSet());
            groupService.update(groupTmp);
            return ajaxJson(resultService.successWithId(groupTmp.getId()));
        }
    }



    /**
     * 操作
     */
    @RequestMapping(value = "method/{method}/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String method,
                         @PathVariable String keyId) {
        BaseEnumManager.MethodEnum methodEnum = null;
        if (StringUtils.equals("Delete", method)) {// 删除
            methodEnum  = BaseEnumManager.MethodEnum.Delete;
        } else if (StringUtils.equals("Enable", method)) {// 启用
            methodEnum  = BaseEnumManager.MethodEnum.Enable;
        } else if (StringUtils.equals("Disenable", method)) {// 禁用
            methodEnum  = BaseEnumManager.MethodEnum.Disenable;
        }
        Result result = groupService.methodEntity(methodEnum, keyId);
        return ajaxJson(result);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        /*
        // 排序
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);*/
        SearchResultPaging searchResult = groupService.pagingGroup(null, null, null, company, BaseEnumManager.StateEnum.Enable);

        List<Group> groupList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Group entity : groupList) {
            Map<String, Object> map = groupService.getListMap(entity);
            dataRows.add(map);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }


    /**
     * 选择群组
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user, @RequestParam(required = false) String sids, Model model) {
        model.addAttribute("sids",sids);
        if (StringUtils.isNotBlank(sids)) {
            String[] pids = StringUtils.split(sids,",");
            ArrayList<Group> groups = new ArrayList<Group>();
            for (String pid : pids) {
                Group group = groupService.get(pid);
                groups.add(group);
            }
            model.addAttribute("selectedGroups",groups);
        }

        return "/main/company/group_dialogs";
    }
}
